package com.cn.wanxi.util;

import com.alibaba.fastjson.JSONObject;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/*")
public class MyFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {


    }

    /**
     * 过滤
     *
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //        1.乱码问题
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("");
//        首先登录和注册页面不能进行拦截，只能拦截后台访问的地址
        String path = req.getServletPath();
        System.out.println(path);
        //之拦截后台"/back/"开头的
        if (path.startsWith("/back/")) {
            HttpSession session = req.getSession();
            String key = req.getParameter("loginUsername");
            String username = (String) session.getAttribute(key);
            if (username == null) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("result", "noLogin");
                resp.getWriter().println(jsonObject);//            resp.sendRedirect("/html/login.html");//重定向
            } else {
                filterChain.doFilter(req, resp);//放行
            }
        } else {
            filterChain.doFilter(req, resp);//放行
        }

    }

    @Override
    public void destroy() {

    }
}
